<?php

// 接口请求的 PHP 范例代码
// 更多语言的范例见 UC2 https://gitee.com/Discuz/UCenter/tree/master/developer

$r = new request();
$r->sample();

class request {

	var $url = 'https://test.72zhan.com/api/restful/';
	var $appid = '18426451';
	var $secret = 'JRT34INS4TTTGNCL';
	var $token = '';

	public function sample() {
		echo '<pre>';

		$ret = $this->_request('/token', []);
		if(!$ret || $ret['ret'] > 0 || empty($ret['token'])) {
			die('接口错误，无法获取 Token');
		}
		$this->token = $ret['token'];

		$ret = $this->_request('/index/forumlist', []);
		if(!$ret || $ret['ret'] > 0) {
			die('接口错误，无法获取 /index/forumlist 接口');
		}

		print_r($ret);

		$ret = $this->_request('/forumdisplay', ['fid' => 2]);
		if(!$ret || $ret['ret'] > 0) {
			die('接口错误，无法获取 /index/forumdisplay 接口');
		}

		print_r($ret);
	}

	private function _request($uri, $post, $validate = false, $unique = false) {
		$nonce = rand(1000, 2000);
		$t = time();
		$headers = [
			'appid' => $this->appid,
			'nonce' => $nonce,
			't' => $t,
			'sign' => base64_encode(hash('sha256', $nonce.$t.$this->secret)),
		];

		if($validate) {//validateData 属性存在时携带的参数
			$post = json_encode($post);
			$headers['validatecode'] = sha1($this->secret.$post);
			$headers['Content-Type'] = 'application/json;charset=utf-8';
			$headers['Content-Length'] = strlen($post);
		}

		if($unique) {//validateUnique 属性存在时携带的参数
			$headers['uniqueid'] = $unique;// 唯一串开发者自定义
		}

		if($this->token) {
			$headers['token'] = $this->token;
		}

		$headersFmt = [];
		foreach($headers as $name => $value) {
			$canonicalName = implode('-', array_map('ucfirst', explode('-', $name)));
			$headersFmt[] = $canonicalName.': '.$value;
		}

		$ch = curl_init();
		curl_setopt_array($ch, [
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_HTTPHEADER => $headersFmt,
			CURLOPT_URL => $this->url.'?'.$uri,
			CURLOPT_POST => 'POST',
			CURLOPT_POSTFIELDS => $post,
			CURLOPT_SSL_VERIFYHOST => false,
			CURLOPT_SSL_VERIFYPEER => false,
		]);
		$response = curl_exec($ch);
		return json_decode($response, true);
	}

}
